package com.kss.app;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.*;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class KssApp {

    protected Shell shell;
    private Label kssAppInfoLable;
    private FormData fdlStepname;
    private  String filePath;
    private  Text text,tokenText,keyInfo;
    private String appName;

    private ExecutorService cachedThreadPool = Executors.newCachedThreadPool();


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            KssApp window = new KssApp();
            window.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void open() {
        final Display display = new Display();
        createContent();
        shell.open();
        shell.layout();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.isDisposed();
    }

    private void createContent() {
        shell = new Shell();
        shell.setSize(600, 800);
        shell.setLocation(Display.getCurrent().getClientArea().width / 2 - shell.getShell().getSize().x/2, Display.getCurrent()
                .getClientArea().height / 2 - shell.getSize().y/2);
        shell.setText("KSS客户端");

        //文件发送区
        Group swtGroup = new Group(shell,SWT.SHADOW_ETCHED_IN);
        swtGroup.setText("文件发送区");
        swtGroup.setBounds(10,10,700,350);

        Label label = new Label(swtGroup, SWT.NONE);
        label.setText("目标站点ID");
        label.setBounds(50, 50, 150, 25);
        text = new Text(swtGroup,SWT.BORDER);
        text.setBounds(200,50,300,25);
        text.setText("B");
        Label tokenLable = new Label(swtGroup, SWT.NONE);
        tokenLable.setText("AppToken");
        tokenLable.setBounds(50, 80, 150, 25);
        tokenText = new Text(swtGroup,SWT.BORDER);
        tokenText.setBounds(200,80,300,25);
        tokenText.setText("bd4fe042-cdc4-4f19-8506-fcb6296c5ecf");
        Button fileButton = new Button(swtGroup,SWT.PUSH);
        fileButton.setText("选择文件");
        fileButton.setBounds(50,120,80,25);
        Label fileLab = new Label(swtGroup, SWT.NONE);
        fileLab.setText("");
        fileLab.setBounds(150, 125, 400, 25);
        Label appListL = new Label(swtGroup, SWT.NONE);
        appListL.setText("目标App");
        appListL.setBounds(50, 160, 150, 25);
        Combo combo=new Combo(swtGroup,SWT.NONE);
        combo.setBounds(200,160,100,25);
        getAppList(combo);
        kssAppInfoLable = new Label(swtGroup, SWT.NONE);
        kssAppInfoLable.setBounds(50,220,400,25);
        kssAppInfoLable.setText("当前客户端信息 ： 站点A -->> App名称： app1");
        getAppInfo();
        Button button = new Button(swtGroup,SWT.PUSH);
        button.setBounds(50,250,120,25);
        button.setText("刷新客户端信息");
        keyInfo = new Text(swtGroup,SWT.BORDER);
        keyInfo.setBounds(50,280,300,25);
        button.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent selectionEvent) {
                getAppInfo();
                super.widgetSelected(selectionEvent);
            }
        });
        fileButton.addSelectionListener(new SelectionListener() {
            @Override
            public void widgetSelected(SelectionEvent selectionEvent) {
                FileDialog filedlg=new FileDialog(shell,SWT.OPEN);
                filePath  = filedlg.open();
                if(!fileLab.isDisposed()) {
                    if(filePath != null) {
                        fileLab.setText(filePath);
                    }
                }
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent selectionEvent) {

            }
        });
        Button keyBtn = new Button(swtGroup,SWT.PUSH);
        keyBtn.setBounds(50,185,80,25);
        keyBtn.setText("发送文件");
        combo.addSelectionListener(new SelectionAdapter(){
            @Override
            public void widgetSelected(SelectionEvent e) {
                String key = ""+combo.getSelection();
                System.out.println("key:"+key);
                String value = (String) combo.getText();
                appName = value;
            }
        });
        keyBtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent selectionEvent) {
                 //获取文件路径 加密上传
                 getKey();
                super.widgetSelected(selectionEvent);
            }
        });
        //文件发送区
        Group getFileGroup = new Group(shell,SWT.SHADOW_ETCHED_IN);
        getFileGroup.setText("文件接收区");
        getFileGroup.setBounds(10,400,500,300);

        Table table = new Table(getFileGroup, SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK);
        table.setBounds(50,50,500,170);
        table.setHeaderVisible(true);
        table.setLinesVisible(true);
        // 创建表头的字符串数组
        String[] tableHeader = {"文件名", "接收App", "发送时间","发送App"};
        for (int i = 0; i < tableHeader.length; i++)
        {
            TableColumn tableColumn = new TableColumn(table, SWT.NONE);
            tableColumn.setText(tableHeader[i]);
            // 设置表头可移动，默认为false
            tableColumn.setMoveable(true);
        }
        getList(tokenText.getText(),table);
        for (int i = 0; i < tableHeader.length; i++)
        {
            table.getColumn(i).pack();
        }
        Button refreshBtn = new Button(getFileGroup,SWT.PUSH);
        refreshBtn.setText("刷新列表");
        refreshBtn.setBounds(50,225,80,25);
        Button downFileBtn = new Button(getFileGroup,SWT.PUSH);
        downFileBtn.setText("下载文件");
        downFileBtn.setBounds(140,225,80,25);
        downFileBtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent selectionEvent) {
                final TableItem [] items = table.getItems();
                for (int i = 0; i < items.length; ++i) {
                    if (items[i].getChecked()){
                        KssData.DataDTO data = (KssData.DataDTO) items[i].getData();
                        decryptFile(data);
                    }
                }

                super.widgetSelected(selectionEvent);
            }
        });
        refreshBtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent selectionEvent) {
                shell.getDisplay().asyncExec(new Runnable() {
                    @Override
                    public void run() {
                        getList(tokenText.getText(),table);
                    }
                });
                super.widgetSelected(selectionEvent);
            }
        });
    }

    private void getAppInfo() {
        String appInfo = HttpUtil.get("http://localhost:9666/kmsApp/getAppInfo?token="+this.tokenText.getText());
        JSONObject object = JSONUtil.parseObj(appInfo);
        Integer code = (Integer) object.get("code");
        if(code == 200) {
            JSONObject data = (JSONObject) object.get("data");
            kssAppInfoLable.setText("当前客户端信息 ： 站点A -->> App名称： "+data.get("name"));
        }
    }

    private void getKey() {
        String siteID = this.text.getText();
        String token = this.tokenText.getText();
        if(StrUtil.isBlank(siteID)) {
            MessageBox dialog=new MessageBox(shell,SWT.OK|SWT.ICON_INFORMATION);
            dialog.setText("提示");
            dialog.setMessage("目标站点不能为空");
            dialog.open();
            return;
        }
        if(StrUtil.isBlank(token)) {
            MessageBox dialog=new MessageBox(shell,SWT.OK|SWT.ICON_INFORMATION);
            dialog.setText("提示");
            dialog.setMessage("app token不能为空");
            dialog.open();
            return;
        }
        if(StrUtil.isBlank(appName)) {
            MessageBox dialog=new MessageBox(shell,SWT.OK|SWT.ICON_INFORMATION);
            dialog.setText("提示");
            dialog.setMessage("目标app不能为空");
            dialog.open();
            return;
        }
        if(StrUtil.isBlank(filePath)) {
            MessageBox dialog=new MessageBox(shell,SWT.OK|SWT.ICON_INFORMATION);
            dialog.setText("提示");
            dialog.setMessage("文件地址不能为空");
            dialog.open();
            return;
        }
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("token",token);
                paramMap.put("siteid",siteID);
                paramMap.put("appName",appName);
                paramMap.put("fileName",FileUtil.getName(filePath));
                String body = HttpRequest.post("http://localhost:9666/newkey").form(paramMap).execute().body();
                JSONObject jsonObject = JSONUtil.parseObj(body);
                Integer code = (Integer) jsonObject.get("code");
                if(code == 200) {
                    JSONObject data = (JSONObject) jsonObject.get("data");
                    //未加密文件路径
                    File oldfile = new File(filePath);
                    File encrypfile = new File("D:\\encryptFiler"+ FileUtil.getName(filePath));
                    try {
                        encrypfile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    AesFile.encryptFile(oldfile, encrypfile, (String) data.get("key"));
                    shell.getDisplay().asyncExec(new Runnable() {
                        @Override
                        public void run() {
                            keyInfo.setText("index="+data.get("index")+"  blockId="+data.get("blockId"));
                        }
                    });
                    shell.getDisplay().asyncExec(new Runnable() {
                        @Override
                        public void run() {
                            MessageBox dialog=new MessageBox(shell,SWT.OK|SWT.ICON_INFORMATION);
                            dialog.setText("提示");
                            dialog.setMessage("文件加密成功"+",路径为"+encrypfile.getAbsolutePath());
                            dialog.open();
                        }
                    });
                }
                else {
                    shell.getDisplay().asyncExec(new Runnable() {
                        @Override
                        public void run() {
                            MessageBox dialog=new MessageBox(shell,SWT.OK|SWT.ICON_INFORMATION);
                            dialog.setText("提示");
                            dialog.setMessage((String) jsonObject.get("message"));
                            dialog.open();
                        }
                    });
                }
            }
        });
    }

    private void getAppList(Combo combo) {
        String appListJson = HttpUtil.get("http://localhost:9666/kmsApp/getAll");
        AppDto appDto = JSONUtil.toBean(appListJson, AppDto.class);
        for (AppDto.DataDTO dataDTO:appDto.getData()) {
            combo.add(dataDTO.getName());
            combo.setData(dataDTO.getName(),dataDTO);
        }
    }

    private void  decryptFile(KssData.DataDTO dataDTO){
        String keyStr = HttpUtil.get("http://localhost:9666/getKeyApp?id="+dataDTO.getKmsId()+"&token="+tokenText.getText());
        JSONObject jsonObject = JSONUtil.parseObj(keyStr);
        Integer code = (Integer) jsonObject.get("code");
        if(code == 200) {
            String data = (String) jsonObject.get("data");
            File oldfile = new File("D:\\"+dataDTO.getFileName());
            File encrypfile = new File("D:\\decryptFile"+dataDTO.getFileName());
            AesFile.decryptFile(oldfile, encrypfile, data);
            shell.getDisplay().asyncExec(new Runnable() {
                @Override
                public void run() {
                    MessageBox dialog=new MessageBox(shell,SWT.OK|SWT.ICON_INFORMATION);
                    dialog.setText("提示");
                    dialog.setMessage("文件解密完成");
                    dialog.open();
                }
            });
        }
        else {
            String message = (String) jsonObject.get("message");
            shell.getDisplay().asyncExec(new Runnable() {
                @Override
                public void run() {
                    MessageBox dialog=new MessageBox(shell,SWT.OK|SWT.ICON_INFORMATION);
                    dialog.setText("提示");
                    dialog.setMessage(message);
                    dialog.open();
                }
            });
        }

    }
    public void getList(String token,Table table) {
        KssData kssDataVo = null;
        TableItem tableItems[] = table.getItems();//得到所有的tableItem
        for(int i = 0; i<tableItems.length; i++)
        {
            tableItems[i].dispose();//释放
        }

        if(token != null) {
             String result2 = HttpUtil.get("http://localhost:9666/selectKmsListById?token="+this.tokenText.getText());
             kssDataVo = JSONUtil.toBean(result2, KssData.class);
        }
        for (KssData.DataDTO dataDTO :kssDataVo.getData()) {
            TableItem item;
            item = new TableItem(table, SWT.NONE);
            item.setData(dataDTO);
            item.setText(new String[]{dataDTO.getFileName(), dataDTO.getDestName() ,dataDTO.getCreateTime(),dataDTO.getName()});
        }
    }
}
